﻿using AdvancedDataGridView;
using SolidWorks.Interop.sldworks;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using static System.Net.WebRequestMethods;
using static System.Windows.Forms.LinkLabel;

namespace SolidworksDLL
{
    public partial class TestFrm : Form
    {
        public TestFrm()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            bool b = SolidWorksHelp.GetSwAPP();
            if (b)
            {
                //MessageBox.Show("获取成功");
            }
            else
            {
                MessageBox.Show("获取失败");
                return;
            }

            string AsmPath = OpenAsm();
            if ("" == AsmPath)
            {
                return;
            }

            richTextBox1.Text = "选择的文件：" + AsmPath;
            //关闭所有打开的文件
            //SolidWorksHelp.swApp.CloseAllDocuments(true);

            ModelDoc2 swModel = null;
            richTextBox1.AppendText(System.Environment.NewLine + "打开装配体文件");
            string result = ModelDocHelp.OpenDoc(AsmPath, ref swModel);
            if (null == swModel)
            {
                MessageBox.Show("打开装配体失败:" + result);
                return;
            }

            AssemblyDoc asmDoc = ModelDocHelp.GetAsm(swModel);
            if (null == asmDoc)
            {
                return;
            }
            richTextBox1.AppendText(System.Environment.NewLine + "获取装配体文件所有子件对象");
            //获取子零部件
            int count = asmDoc.GetComponentCount(true);
            if (count == 0)
            {
                return;
            }

            object[] components = (object[])asmDoc.GetComponents(true);
            foreach (Component2 item in components)
            {
                bool b1 = item.IsEnvelope(); //封套
                bool b2 = item.IsSuppressed();//压缩
                int v = item.Visible; //可见性
                string name = item.Name2;//名称
                string path = item.GetPathName(); //路径
                //richTextBox1.AppendText(System.Environment.NewLine + "子件名称：" + name + ",路径：" + path);
            }

            //获取零部件的依赖
            richTextBox1.AppendText(System.Environment.NewLine + "获取零部件参考信息");
            object[] depends = (object[])SolidWorksHelp.swApp.GetDocumentDependencies2(AsmPath, true, true, false);

            if (depends == null)
            {
                return;
            }

            for (int i = 0; i < depends.Length; i = i + 2)
            {
                string name = (string)depends[i];//名称
                string path = (string)depends[i + 1]; //路径

                //richTextBox1.AppendText(System.Environment.NewLine + "参考名称：" + name + ",路径：" + path);
            }

            List<string> modelPaths = ModelDocHelp.GetAllDoc();

            richTextBox1.AppendText(System.Environment.NewLine + "非还原状态所有打开文件数量：" + modelPaths.Count.ToString());
            //轻化到还原状态
            asmDoc.ResolveAllLightweight();
            modelPaths = ModelDocHelp.GetAllDoc();

            richTextBox1.AppendText(System.Environment.NewLine + "还原状态所有打开文件数量：" + modelPaths.Count.ToString());
        }

        private string OpenAsm()
        {
            openFileDialog1.Filter = "SolidWorks装配体文件|*.sldasm";
            openFileDialog1.FileName = "";
            var result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                return openFileDialog1.FileName;
            }
            return "";
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            bool b = SolidWorksHelp.GetSwAPP();
            if (b)
            {
                //MessageBox.Show("获取成功");
            }
            else
            {
                MessageBox.Show("获取失败");
                return;
            }

            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            if (null == swModel)
            {
                MessageBox.Show("打开模型失败");
                return;
            }

            string cfgName = swModel.GetActiveConfiguration().Name;

            string th = swModel.CustomInfo2[cfgName, "图号"];
            swModel.AddCustomInfo3(cfgName, "图号1", 30, "123456");//只有不存在的属性名称才会生效
            swModel.DeleteCustomInfo2(cfgName, "图号1");
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            bool b = SolidWorksHelp.GetSwAPP();
            if (b)
            {
                //MessageBox.Show("获取成功");
            }
            else
            {
                MessageBox.Show("获取失败");
                return;
            }

            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            if (null == swModel)
            {
                MessageBox.Show("打开模型失败");
                return;
            }

            Dictionary<string, string> ptyDict = new Dictionary<string, string>();
            CustomPryHelp.GetAllPryDict(swModel, "", ref ptyDict);

            List<Configuration> configurations = ConfigurationHelp.GetAllCfg(swModel);
            foreach (var item in configurations)
            {
                CustomPryHelp.ClearPry(swModel, item.Name);
                CustomPryHelp.AddPryDict(swModel, item.Name, ptyDict);
            }
        }

        public bool CheckSW()
        {
            bool b = SolidWorksHelp.GetSwAPP();
            if (b)
            {
                //MessageBox.Show("获取成功");
            }
            else
            {
                MessageBox.Show("获取失败");
                return b;
            }

            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            if (null == swModel)
            {
                MessageBox.Show("打开模型失败");
                return false;
            }

            return true;
        }

        private void Button4_Click(object sender, EventArgs e)
        {
            if (comboBox1.Text == "")
            {
                MessageBox.Show("请选择一种转换格式");
                return;
            }
            if (CheckSW() == false)
            {
                return;
            }
            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            string path = swModel.GetPathName();
            if (path == "")
            {
                MessageBox.Show("请先保存当前文件");
                return;
            }
            string ext = comboBox1.Text.ToUpper();
            string fileName = Path.GetFileNameWithoutExtension(path);
            string dir = Path.GetDirectoryName(path);
            FileConverterHelp.ConvertFile(swModel, dir + @"\" + fileName + ext);
        }

        private void Button5_Click(object sender, EventArgs e)
        {
            PrintFeature(true);
        }

        private void Button6_Click(object sender, EventArgs e)
        {
            PrintFeature(false);
        }

        public void PrintFeature(bool topOnly)
        {
            if (CheckSW() == false)
            {
                return;
            }
            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            List<FeatureData> featureData = FeatureHelp.GetTopFeature(swModel, topOnly);
            foreach (var item in featureData)
            {
                TraPrint(item);
            }
        }

        public void TraPrint(FeatureData featureData)
        {
            richTextBox1.AppendText(System.Environment.NewLine + featureData.feature.Name);
            if (featureData.childrenFeature != null && featureData.childrenFeature.Count > 0)
            {
                foreach (var item in featureData.childrenFeature)
                {
                    TraPrint(item);
                }
            }
        }

        private void Button7_Click(object sender, EventArgs e)
        {
            if (CheckSW() == false)
            {
                return;
            }
            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            TreeItemData treeItemData = TreeItemHelp.GetAllNode(swModel);
            TraPrint(treeItemData);
        }

        public void TraPrint(TreeItemData featureData)
        {
            richTextBox1.AppendText(System.Environment.NewLine + featureData.node.Text);
            if (featureData.childrenNode != null && featureData.childrenNode.Count > 0)
            {
                foreach (var item in featureData.childrenNode)
                {
                    TraPrint(item);
                }
            }
        }

        private void Button8_Click(object sender, EventArgs e)
        {
            if (CheckSW() == false)
            {
                return;
            }
            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            AssemblyDoc assemblyDoc = ModelDocHelp.GetAsm(swModel);
            CompData compData = ComponentHelp.GetComponents(assemblyDoc);
            treeView1.Nodes.Clear();

            TreeNode rootNode = treeView1.Nodes.Add(compData.component.Name2);
            TraNode(rootNode, compData);
        }

        public void TraNode(TreeNode parNode, CompData parData)
        {
            foreach (var item in parData.childrenComp)
            {
                TreeNode newNode = parNode.Nodes.Add(item.component.Name2);
                TraNode(newNode, item);
            }
        }

        private void Button9_Click(object sender, EventArgs e)
        {
            if (CheckSW() == false)
            {
                return;
            }
            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            AssemblyDoc assemblyDoc = ModelDocHelp.GetAsm(swModel);
            CompData compData = ComponentHelp.GetComponents(assemblyDoc);
            treeGridView1.Nodes.Clear();

            TreeGridNode rootNode = treeGridView1.Nodes.Add(compData.component.Name2);
            rootNode.ImageIndex = 0;
            rootNode.Cells[1].Value = "根";
            TraNode(rootNode, compData);
        }

        public void TraNode(TreeGridNode parNode, CompData parData)
        {
            foreach (var item in parData.childrenComp)
            {
                TreeGridNode newNode = parNode.Nodes.Add(item.component.Name2);
                if (item.childrenComp != null && item.childrenComp.Count > 0)
                {
                    newNode.Cells[1].Value = "装配体";
                    newNode.ImageIndex = 0;
                }
                else
                {
                    newNode.Cells[1].Value = "零件";
                    newNode.ImageIndex = 1;
                }

                TraNode(newNode, item);
            }
        }

        private void Button10_Click(object sender, EventArgs e)
        {
            if (CheckSW() == false)
            {
                return;
            }
            DateTime dateTime = DateTime.Now;

            richTextBox1.AppendText(System.Environment.NewLine + "开始时间：" + dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            TreeItemData itemData = TreeItemHelp.GetAllNode(swModel);
            treeGridView1.Nodes.Clear();

            TreeGridNode rootNode = treeGridView1.Nodes.Add(itemData.node.Text);
            rootNode.ImageIndex = 0;
            rootNode.Cells[1].Value = "根";
            TraNode(rootNode, itemData);

            DateTime dateTime1 = DateTime.Now;

            richTextBox1.AppendText(System.Environment.NewLine + "结束时间：" + dateTime1.ToString("yyyy-MM-dd HH:mm:ss"));
            richTextBox1.AppendText(System.Environment.NewLine + "总时间：" + (dateTime1 - dateTime).TotalSeconds.ToString());
        }

        public void TraNode(TreeGridNode parNode, TreeItemData parData)
        {
            foreach (var item in parData.childrenNode)
            {
                TreeGridNode newNode = parNode.Nodes.Add(item.node.Text);

                int type = item.node.ObjectType;
                if (type == 1)
                {
                    Feature feature1 = (Feature)item.node.Object;
                    newNode.Cells[1].Value = feature1.GetTypeName();
                }
                else if (type == 2)
                {
                    newNode.Cells[1].Value = "子件";
                }

                if (item.childrenNode != null && item.childrenNode.Count > 0)
                {
                    newNode.ImageIndex = 0;
                }
                else
                {
                    newNode.ImageIndex = 1;
                }

                TraNode(newNode, item);

                //按顺序输出零部件的注意事项
                //1.排除“历史记录”所有子节点
                //2.如果是文件夹特征，将文件夹特征的上级子件作为父亲
                //3.输出BOM 的话 进行相同数据的计数
            }
        }

        private void Button11_Click(object sender, EventArgs e)
        {
            if (CheckSW() == false)
            {
                return;
            }
            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            if (swModel.GetType() != 3)
            {
                return;
            }
            DateTime dateTime = DateTime.Now;
            Begin(ref dateTime);
            treeView1.Nodes.Clear();
            DrawingDoc drawingDoc = (DrawingDoc)swModel;

            TreeNode rootNode = treeView1.Nodes.Add(swModel.GetTitle());
            List<Sheet> sheets = DrawingsHelp.GetSheets(drawingDoc);
            foreach (var sheet in sheets)
            {
                TreeNode sheetNode = rootNode.Nodes.Add(sheet.GetName());
                List<SolidWorks.Interop.sldworks.View> views = DrawingsHelp.GetSheetViews(drawingDoc, sheet.GetName());
                foreach (var view in views)
                {
                    TreeNode viewNode = sheetNode.Nodes.Add(view.Name + "<" + view.Type.ToString() + ">");
                }
            }
            End(dateTime);
        }

        public void Begin(ref DateTime dateTime)
        {
            dateTime = DateTime.Now;

            richTextBox1.AppendText(System.Environment.NewLine + "开始时间：" + dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        public void End(DateTime dateTime)
        {
            DateTime dateTime1 = DateTime.Now;

            richTextBox1.AppendText(System.Environment.NewLine + "结束时间：" + dateTime1.ToString("yyyy-MM-dd HH:mm:ss"));
            richTextBox1.AppendText(System.Environment.NewLine + "总时间：" + (dateTime1 - dateTime).TotalSeconds.ToString());
        }

        private void Button12_Click(object sender, EventArgs e)
        {
            if (CheckSW() == false)
            {
                return;
            }
            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            if (swModel.GetType() != 3)
            {
                return;
            }
            DateTime dateTime = DateTime.Now;
            Begin(ref dateTime);

            DrawingDoc drawingDoc = (DrawingDoc)swModel;

            bool b = swModel.Extension.SelectByID2("细节项目105@图纸1", "ANNOTATIONTABLES", 0, 0, 0, false, 0, null, 0);
            SelectionMgr swSelectionMgr = (SelectionMgr)swModel.SelectionManager;
            TableAnnotation tableAnnotation = (TableAnnotation)swSelectionMgr.GetSelectedObject6(1, -1);

            //TableAnnotation tableAnnotation = DrawingsHelp.GetViewBom(drawingDoc, "工程图视图1");
            if (tableAnnotation == null)
            {
                return;
            }
            List<List<string>> bomData = DrawingsHelp.GetViewBomData(tableAnnotation);
            foreach (var item in bomData)
            {
                richTextBox1.AppendText(System.Environment.NewLine);
                foreach (var item1 in item)
                {
                    richTextBox1.AppendText(item1 + "|");
                }
            }
            End(dateTime);
        }

        private void Button13_Click(object sender, EventArgs e)
        {
            if (CheckSW() == false)
            {
                return;
            }
            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            if (swModel.GetType() != 3)
            {
                return;
            }
            DateTime dateTime = DateTime.Now;
            Begin(ref dateTime);

            DrawingDoc drawingDoc = (DrawingDoc)swModel;

            SolidWorks.Interop.sldworks.View view = DrawingsHelp.GetSheetView(drawingDoc, "工程图视图1");
            List<DisplayDimension> displayDimensions = DrawingsHelp.GetViewsDim(view);
            foreach (var item in displayDimensions)
            {
                Dimension dimension = item.GetDimension();

                richTextBox1.AppendText(System.Environment.NewLine + "尺寸名称：" + dimension.Name + ",尺寸值：" + (dimension.SystemValue * 1000).ToString() + "mm");
            }

            End(dateTime);
        }

        private void Button14_Click(object sender, EventArgs e)
        {
            if (CheckSW() == false)
            {
                return;
            }
            ModelDoc2 swModel = SolidWorksHelp.swApp.ActiveDoc;
            if (swModel.GetType() != 1)
            {
                return;
            }
            DateTime dateTime = DateTime.Now;
            Begin(ref dateTime);

            PartDoc partDoc = (PartDoc)swModel;

            //body
            List<Body2> bodies = BodyHelp.GetAllBody(partDoc);
            if (bodies == null)
            {
                End(dateTime);
                return;
            }
            foreach (var item in bodies)
            {
                richTextBox1.AppendText(System.Environment.NewLine + "体：" + item.Name);
                //所有面
                List<Face2> faces = BodyHelp.GetAllFaces(item);
                if (faces == null)
                {
                    End(dateTime);
                    continue;
                }
                for (int i = 0; i < faces.Count; i++)
                {
                    richTextBox1.AppendText(System.Environment.NewLine + "面：" + i.ToString());

                    List<Edge> edges = BodyHelp.GetAllEdges(faces[i]);
                    if (edges == null)
                    {
                        End(dateTime);
                        continue;
                    }
                    for (int j = 0; j < edges.Count; j++)
                    {
                        richTextBox1.AppendText(System.Environment.NewLine + "边：" + j.ToString());

                        List<Vertex> verteices = BodyHelp.GetAllVertexs(edges[j]);
                        if (verteices == null)
                        {
                            End(dateTime);
                            continue;
                        }

                        foreach (var item2 in verteices)
                        {
                            double[] point = item2.GetPoint();

                            richTextBox1.AppendText(System.Environment.NewLine +
                                "点：X" + point[0].ToString() +
                                 ",Y" + point[1].ToString() +
                                  "Z" + point[2].ToString());
                        }
                    }
                }
            }

            End(dateTime);
        }

        private void TestFrm_Load(object sender, EventArgs e)
        {
        }
    }
}